<?php

class Preload
{
    function __construct()
    {
    }
    
    function parse()
    {
        $module = isset($_GET['m']) ? $_GET['m'] : '';
        $action = isset($_GET['a']) ? $_GET['a'] : '';
        $this->_rute = array( 
                            'module' => $module,
                            'action' => $action,
                        );
                        
        if( !$module )
        {
            return false;
        }

        $file = BASE_PATH.'/Module/'.$module.'.php';
        if( ! is_file( $file ) )
        {
            $file .= '1';
            if( !is_file( $file ) )
            {
                throw New Exception( "can't find module [{$file}]." ) ;
            }
        }
            
        require_once $file;
        
        if( ! class_exists( $module ) )
        {
            throw New Exception( "can't find class [{$module}]." ) ;
        }
        
        if( ! method_exists( $module, $action ) )
        {
            throw New Exception( "can't find action [{$action}] in class [{$module}]." ) ;
        }
        
        $obj = new $module();
        $obj->$action();
        
        return true;
    }
    
    static $_instance = null;
    static function getInstance()
    {
        if( self::$_instance === null )
        {
            self::$_instance = new self() ;
        }
        
        return self::$_instance ;
    }
    
    function getRute()
    {
        return $this->_rute;
    }
    
    function getTools()
    {
        $dir = BASE_PATH.'/Module/';        
        $modules = array();
        $files = scandir( $dir );

		$escape = array( '', 'Module', 'Home', 'Funcs' );
        foreach( $files as $file )
        {
            if( substr( $file, -3) != 'php' ) continue;
			$arr = explode( '.', $file ); 
			if( in_array( $arr[0], $escape ) )
			{
				continue;
			}

            $file = $dir . $file;
			if( !preg_match( '/^[a-zA-Z]*\.[PHph]*$/', basename($file) ) )
			{
				continue;
			}
            if( is_file( $file ) && ( $name = $this->isOkModule( $file ) ) )
            {
                $modules[] = $name;
            }
        }

        return $modules;
    }
    
    private function isOkModule( $file )
    {
		if( ! is_file( $file ) )
		{
			$this->info( " can't find {$file}. " );
			return false;
		}
        require_once $file;
        $fileName = basename( $file );
        $fileInfo = explode( '.', $fileName );
        $name = $fileInfo[0];
        if( class_exists( $name ) 
            && method_exists( $name, 'display' ) )
        {
            return $name;
        }
        return false;
    }
}
